import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Form, Input, Button, Tabs } from 'antd';
import { UserOutlined, LockOutlined, PhoneOutlined } from '@ant-design/icons';
import { authAPI } from '../../services/api';
import { setUserToken, setUserInfo } from '../../utils/auth';
import { giveRegisterPoints } from '../../utils/points';
import { initializeMockData } from '../../services/mockData';
import { message } from '../../utils/message';


const { TabPane } = Tabs;

const MobileLogin = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('login');

  const from = location.state?.from?.pathname || '/app';

  // 登录处理
  const handleLogin = async (values) => {
    setLoading(true);
    try {
      const response = await authAPI.login(values.username, values.password);
      if (response.success) {
        setUserToken(response.data.token);
        setUserInfo(response.data.user);
        message.success('登录成功');
        navigate(from, { replace: true });
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('登录失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 注册处理
  const handleRegister = async (values) => {
    if (values.password !== values.confirmPassword) {
      message.error('两次输入的密码不一致');
      return;
    }

    setLoading(true);
    try {
      const response = await authAPI.register({
        username: values.username,
        password: values.password,
        nickname: values.nickname || values.username,
        phone: values.phone,
        email: values.email
      });
      
      if (response.success) {
        setUserToken(response.data.token);
        setUserInfo(response.data.user);
        giveRegisterPoints();
        message.success('注册成功，获得100积分奖励！');
        navigate(from, { replace: true });
      } else {
        message.error(response.message || '注册失败，请稍后重试');
      }
    } catch (error) {
      console.error('注册失败:', error);
      message.error('注册失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="admin-login-container"
      style={{
        margin: '0 auto',
        width: '375px',
        background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <div
        className="login-card"
        style={{
          background: '#fff',
          borderRadius: 16,
          boxShadow: '0 8px 32px rgba(60,60,120,0.12)',
          padding: '40px 32px 32px 32px',
          width: 360,
          maxWidth: '90vw',
        }}
      >
        <div
          className="mobile-login-logo"
          style={{
            textAlign: 'center',
            margin: '0 0 24px 0',
          }}
        >
          <img
            src="https://img.icons8.com/color/96/000000/shopping-cart.png"
            alt="logo"
            style={{ width: 64, height: 64, marginBottom: 8 }}
          />
          <h1
            className="mobile-login-title"
            style={{
              marginBottom: 4,
              fontWeight: 700,
              fontSize: 28,
              color: '#222',
              letterSpacing: 2,
              
            }}
          >
            欢迎来到商城
          </h1>
          <p
            className="mobile-login-subtitle"
            style={{
              color: '#888',
              fontSize: 15,
              marginBottom: 0,
            }}
          >
            发现更多精彩商品
          </p>
        </div>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          centered
          size="large"
          tabBarStyle={{
            marginBottom: 32,
            fontWeight: 600,
            fontSize: 18,
          }}
        >
          <TabPane tab="登录" key="login">
            <Form
              name="login"
              onFinish={handleLogin}
              autoComplete="off"
              layout="vertical"
              size="large"
              style={{ marginTop: 8 }}
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, message: '用户名至少3个字符' },
                ]}
              >
                <Input
                  prefix={<UserOutlined style={{ color: '#1890ff' }} />}
                  placeholder="用户名"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 4, message: '密码至少4个字符' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#1890ff' }} />}
                  placeholder="密码"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                  style={{
                    borderRadius: 8,
                    fontWeight: 600,
                    fontSize: 16,
                    height: 44,
                  }}
                >
                  登录
                </Button>
              </Form.Item>
            </Form>

            <div style={{ textAlign: 'center', marginTop: 8 }}>
              <Button
                type="link"
                onClick={() => message.info('忘记密码功能开发中')}
                style={{ color: '#1890ff', fontWeight: 500 }}
              >
                忘记密码？
              </Button>
            </div>
          </TabPane>

          <TabPane tab="注册" key="register">
            <Form
              name="register"
              onFinish={handleRegister}
              autoComplete="off"
              layout="vertical"
              size="large"
              style={{ marginTop: 8 }}
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, message: '用户名至少3个字符' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
                ]}
              >
                <Input
                  prefix={<UserOutlined style={{ color: '#1890ff' }} />}
                  placeholder="用户名"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item
                name="nickname"
                rules={[
                  { required: true, message: '请输入昵称' },
                  { min: 2, message: '昵称至少2个字符' },
                ]}
              >
                <Input
                  prefix={<UserOutlined style={{ color: '#52c41a' }} />}
                  placeholder="昵称"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
                ]}
              >
                <Input
                  prefix={<PhoneOutlined style={{ color: '#faad14' }} />}
                  placeholder="手机号"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入正确的邮箱格式' },
                ]}
              >
                <Input
                  placeholder="邮箱"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6个字符' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#1890ff' }} />}
                  placeholder="密码"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                rules={[
                  { required: true, message: '请确认密码' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#1890ff' }} />}
                  placeholder="确认密码"
                  style={{ borderRadius: 8 }}
                />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                  style={{
                    borderRadius: 8,
                    fontWeight: 600,
                    fontSize: 16,
                    height: 44,
                  }}
                >
                  注册
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
        <div
          className="login-tips"
          style={{
            textAlign: 'center',
            marginTop: 24,
            color: '#888',
            fontSize: 13,
            lineHeight: 1.7,
          }}
        >
          <p>
            登录即表示同意
            <a href="#1" style={{ color: '#1890ff', margin: '0 4px' }}>《用户协议》</a>
            和
            <a href="#1" style={{ color: '#1890ff', margin: '0 4px' }}>《隐私政策》</a>
          </p>
          {/* <p style={{ marginTop: 8, color: '#aaa', fontSize: 12 }}>
            测试账号：<span style={{ color: '#222' }}></span> 或 <span style={{ color: '#222' }}>admin / admin</span>
          </p> */}
          {/* <Button
            type="link"
            onClick={async () => {
              try {
                await initializeMockData();
                message.success('初始化数据成功！');
              } catch (e) {
                message.error('初始化失败，请重试');
              }
            }}
            style={{ color: '#faad14', fontWeight: 500, marginTop: 8 }}
          >
            初始化演示数据
          </Button> */}
        </div>
      </div>
    </div>
  );
};

export default MobileLogin; 